﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using NNS.Framework;
using NNS.Utils;
using QLTB.BusinessLayer;
using QLTB.Sercurity.Entity;
using QLTB.Sercurity.UI;

namespace QLTB.Sercurity
{
    public enum LoginStyle
    {
        Login,
        Logout
    }

    public partial class frmLogin : XtraForm
    {
        private frmDBOption DbOption; //=new frmDBOption();
        private int donvi;
        private string user;

        public frmLogin()
        {
            InitializeComponent();
            readmember();
            Style = LoginStyle.Logout;
            Completed += frmLogin_Completed;
            Userloaded += frmLogin_Userloaded;
            Logined += frmLogin_Logined;
            Error += frmLogin_Error;
        }

        public LoginStyle Style { get; set; }

        private event EventHandler Completed;
        private event EventHandler Userloaded;
        public event EventHandler Logined;
        private event EventHandler<LoginEventArgs> Error;
        public event EventHandler Userlogined;

        private void OnUserlogined(EventArgs e)
        {
            EventHandler handler = Userlogined;
            if (handler != null) handler(this, e);
        }

        private void OnError(LoginEventArgs e)
        {
            EventHandler<LoginEventArgs> _handler = Error;
            if (_handler != null) _handler(this, e);
        }


        private void OnLogined(EventArgs e)
        {
            EventHandler _handler = Logined;
            if (_handler != null) _handler(this, e);
        }

        private void Onloaded(EventArgs e)
        {
            EventHandler _userloaded = Userloaded;
            if (_userloaded != null) _userloaded(this, e);
        }

        private void OnCompleted(EventArgs e)
        {
            EventHandler _completed = Completed;
            if (_completed != null) _completed(this, e);
        }

        private void readmember()
        {
            if (File.Exists(Application.StartupPath + "\\info.xml"))
            {
                var ds = new dsLogin();
                ds.LOGIN.ReadXml(Application.StartupPath + "\\info.xml");
                if (ds.LOGIN.Count > 0)
                {
                    chxRemember.Checked = (bool) ds.LOGIN.Rows[0][ds.LOGIN.nhoColumn];
                    donvi = (int) ds.LOGIN.Rows[0][ds.LOGIN.donviColumn];
                    user = ds.LOGIN.Rows[0][ds.LOGIN.tenuserColumn] as string;
                    txtmatkhau.Text = ds.LOGIN.Rows[0][ds.LOGIN.matkhauColumn] as string;
                }
            }
        }

        private void Save()
        {
            if (chxRemember.Checked)
            {
                var ds = new dsLogin();
                ds.LOGIN.AddLOGINRow((int) txtDonvi.EditValue, txttaikhoan.EditValue as string, txtmatkhau.Text,
                                     chxRemember.Checked);
                ds.LOGIN.WriteXml(Application.StartupPath + "\\info.xml");
            }
        }

        private void frmLogin_Error(object sender, LoginEventArgs e)
        {
            //throw new NotImplementedException();
            if (InvokeRequired)
            {
                EventHandler<LoginEventArgs> ev = frmLogin_Error;
                Invoke(ev, new[] {sender, e});
            }
            else
            {
                DisableControl(true);
                MyBox.ShowWarning(this, e.Message, "Đăng nhập");
                txttaikhoan.Focus();
            }
        }

        private void frmLogin_Logined(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            if (InvokeRequired)
            {
                EventHandler ev = frmLogin_Logined;
                Invoke(ev, new[] {sender, e});
            }
            else
            {
                DisableControl(true);
                if (MyLogin.Current != null)
                {
                    MyLogin.Original = LoginBO.FromTBL_nhanvien(MyLogin.Current);
                }
                MyLogin.Original.Date = DateTime.Now;
                Style = LoginStyle.Login;
                Save();
                Hide();
                OnUserlogined(null);
            }
        }

        private void frmLogin_Userloaded(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            if (InvokeRequired)
            {
                EventHandler ev = frmLogin_Userloaded;
                Invoke(ev, new[] {sender, e});
            }
            else
            {
                DisableControl(true);
                if (dsNguoiDung.TBL_nhanvien.Count > 0)
                {
                    if (txttaikhoan.Text.Length == 0)
                    {
                        txttaikhoan.EditValue = dsNguoiDung.TBL_nhanvien.Rows[0]["tenuser"];
                        if (chxRemember.Checked)
                        {
                            txttaikhoan.EditValue = user;
                        }
                    }
                }

                CheckVersion();
            }
        }

        private void CheckVersion()
        {
            var bl = new TBL_ThongtinBL();
            if (bl.ThongTin != null)
            {
                if (bl.ThongTin.AppVersion > Program.Version)
                {
                    btnUpdate.Visible = true;
                }
            }
        }

        private void frmLogin_Completed(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                EventHandler ev = frmLogin_Completed;
                Invoke(ev, new[] {sender, e});
            }
            else
            {
                DisableControl(true);
                if (dsDonVi.TBL_DONVI.Count > 0)
                {
                    if (txtDonvi.Text.Length == 0)
                    {
                        if (chxRemember.Checked)
                        {
                            txtDonvi.EditValue = donvi;
                        }
                        else
                        {
                            txtDonvi.EditValue = dsDonVi.TBL_DONVI.Rows[0]["MaDonVi"];
                        }
                    }
                }
            }

            //throw new NotImplementedException();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            lblMessage.Caption = "";
            if (!MyLib.IsAddressAvailable("vnexpress.net"))
            {
                lblMessage.Caption = "Máy đang Offline";
            }

            DisableControl(false);
            NapDV();
        }

        private void NapUser()
        {
            if (txtDonvi.Text.Length == 0) return;
            DisableControl(false);
            try
            {
                tBL_nhanvienTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_nhanvienTableAdapter.FillBy(dsNguoiDung.TBL_nhanvien, txtDonvi.EditValue as int?);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Đăng nhập");
            }
            Onloaded(null);
        }

        private void NapDV()
        {
            try
            {
                tBL_DONVITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_DONVITableAdapter.Fill(dsDonVi.TBL_DONVI);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Đăng nhập");
            }

            OnCompleted(null);
        }

        private void DisableControl(bool enable)
        {
            txtDonvi.Enabled = enable;
            txttaikhoan.Enabled = enable;
            txtmatkhau.Enabled = enable;
            btnLogin.Enabled = enable;
            btnOption.Enabled = enable;
            txtTientrinh.Visibility = enable ? BarItemVisibility.Never : BarItemVisibility.Always;
        }

        private void txtDonvi_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDonvi.Text.Length == 0) return;
            DisableControl(false);
            NapUser();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void txtDonvi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(null, null);
            }
        }

        private void login()
        {
            //Kiem tra kết nối
            if (!SqlHelperSmart.Check(true))
            {
                OnError(new LoginEventArgs {Message = "Không kết nối với máy chủ!"});
                return;
            }
            string result = MyLogin.CheckAccount(txttaikhoan.Text, txtmatkhau.Text);
            if (result != "OK")
            {
                OnError(new LoginEventArgs {Message = result});
                return;
            }

            OnLogined(null);
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (btnUpdate.Visible)
            {
                MyBox.ShowWarning("Phiên bản hiện tại đã quá cũ!\nVui lòng cập nhật phiên bản mới.", "Quản lý thiết bị");
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
            DisableControl(false);
            if (txttaikhoan.Text.Trim().Length == 0)
            {
                //XtraMessageBox.Show("Username field cannot be left blank.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);

                txttaikhoan.Focus();
                DisableControl(true);
                Cursor.Current = Cursors.Default;
                return;
            }

            login();
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            if (Style == LoginStyle.Login)
            {
            }
            else if (Style == LoginStyle.Logout)
            {
                Environment.Exit(0);
            }

            e.Cancel = !Program._exit;
        }

        private void btnOption_Click(object sender, EventArgs e)
        {
            if (DbOption == null)
            {
                DbOption = new frmDBOption();
                DbOption.SaveChanged += DbOption_SaveChanged;
                DbOption.FirstRun = false;
            }
            DbOption.ShowDialog();
        }

        private void DbOption_SaveChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            DisableControl(false);
            NapDV();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\Update.exe"))
            {
                Process.Start(Application.StartupPath + "\\Update.exe");
            }
        }
    }

    internal class LoginEventArgs : EventArgs
    {
        public string Message { get; set; }
    }
}